package com.mdp.lcode.ctrl;

import java.util.*;
import java.util.stream.Collectors;

import com.mdp.lcode.entity.FormDefVo;
import com.mdp.lcode.service.FormDefService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.*;

import com.mdp.core.entity.Result;
import com.mdp.core.entity.LangTips;
import com.mdp.core.err.BizException;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.mdp.swagger.ApiEntityParams;
import springfox.documentation.annotations.ApiIgnore;

import com.mdp.lcode.service.FormFieldService;
import com.mdp.lcode.entity.FormField;

@RestController
@RequestMapping(value="/**/lcode/formField")
@Api(tags={"表单字段定义-操作接口"})
public class FormFieldController {
	
	static Logger logger =LoggerFactory.getLogger(FormFieldController.class);
	
	@Autowired
	private FormFieldService formFieldService;

	@Autowired
	private FormDefService formDefService;


	@ApiOperation( value = "表单字段定义-查询列表",notes=" ")
	@ApiEntityParams(FormField.class)
	@ApiResponses({
		@ApiResponse(code = 200,response=FormField.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'错误码'},total:总记录数,data:[数据对象1,数据对象2,...]}")
	})
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public Result listFormField(@ApiIgnore @RequestParam Map<String,Object> params){
		try {
			User user=LoginUtils.getCurrentUserInfo();
			String formId=(String) params.get("formId");
			if(!StringUtils.hasText(formId)){
				return Result.error("formId-0","formId不能为空");
			}
			FormDefVo formDefVo=this.formFieldService.getFormFieldFromCache(formId);
			if(formDefVo==null ) {
				return Result.ok("query-ok","查询成功").setTotal(0);
			}
 			return Result.ok("query-ok","查询成功").setData(formDefVo).setTotal(1).put("formDef",formDefVo.getFormDef());
		}catch (BizException e) {
			return Result.error(e);
		}catch (Exception e) {
			return Result.error(e);
		}
	}
	

	@ApiOperation( value = "表单字段定义-新增",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200,response=FormField.class,message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	}) 
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public Result addFormField(@RequestBody FormField formField) {
		formDefService.checkFormDefQx(formField.getFormId(),LoginUtils.getCurrentUserInfo());
		formFieldService.save(formField);
         return Result.ok("add-ok","添加成功！");
	}

	@ApiOperation( value = "表单字段定义-删除",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}}")
	}) 
	@RequestMapping(value="/del",method=RequestMethod.POST)
	public Result delFormField(@RequestBody FormField formField){

		formDefService.checkFormDefQx(formField.getFormId(),LoginUtils.getCurrentUserInfo());
		formFieldService.removeById(formField);
        return Result.ok("del-ok","删除成功！");
	}

	@ApiOperation( value = "表单字段定义-修改",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200,response=FormField.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	}) 
	@RequestMapping(value="/edit",method=RequestMethod.POST)
	public Result editFormField(@RequestBody FormField formField) {
		formDefService.checkFormDefQx(formField.getFormId(),LoginUtils.getCurrentUserInfo());
		formFieldService.updateById(formField);
        return Result.ok("edit-ok","修改成功！");
	}

    @ApiOperation( value = "表单字段定义-批量修改某些字段",notes="")
    @ApiEntityParams( value = FormField.class, props={ }, remark = "表单字段定义", paramType = "body" )
	@ApiResponses({
			@ApiResponse(code = 200,response=FormField.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
	})
	@RequestMapping(value="/editSomeFields",method=RequestMethod.POST)
	public Result editSomeFields( @ApiIgnore @RequestBody Map<String,Object> params) {
        try{
            User user= LoginUtils.getCurrentUserInfo();
            formFieldService.editSomeFields(params);
            return Result.ok("edit-ok","更新成功");
        }catch (BizException e) {
            logger.error("",e);
            return Result.error(e);
        }catch (Exception e) {
            logger.error("",e);
            return Result.error(e);
        }
	}

	@ApiOperation( value = "表单字段定义-批量删除",notes=" ")
	@ApiResponses({
		@ApiResponse(code = 200, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'}")
	}) 
	@RequestMapping(value="/batchDel",method=RequestMethod.POST)
	public Result batchDelFormField(@RequestBody List<FormField> formFields) {
	    User user= LoginUtils.getCurrentUserInfo();
        try{ 
            if(formFields.size()<=0){
                return Result.error("formField-batchDel-data-err-0","请上送待删除数据列表");
            }
             List<FormField> datasDb=formFieldService.listByIds(formFields.stream().map(i-> i.getId() ).collect(Collectors.toList()));

            List<FormField> can=new ArrayList<>();
            List<FormField> no=new ArrayList<>();
            for (FormField data : datasDb) {
                if(true){
                    can.add(data);
                }else{
                    no.add(data);
                } 
            }
            List<String> msgs=new ArrayList<>();
            if(can.size()>0){
                formFieldService.removeByIds(can);
                msgs.add(LangTips.transMsg("del-ok-num","成功删除%s条数据.",can.size()));
            }
    
            if(no.size()>0){ 
                msgs.add(LangTips.transMsg("not-allow-del-num","以下%s条数据不能删除:【%s】",no.size(),no.stream().map(i-> i.getId() ).collect(Collectors.joining(","))));
            }
            if(can.size()>0){
                 return Result.ok(msgs.stream().collect(Collectors.joining()));
            }else {
                return Result.error(msgs.stream().collect(Collectors.joining()));
            } 
        }catch (BizException e) { 
           return Result.error(e);
        }catch (Exception e) {
            return Result.error(e);
        }


	} 

	@ApiOperation( value = "表单字段定义-根据主键查询一条数据",notes=" ")
     @ApiResponses({
            @ApiResponse(code = 200,response=FormField.class, message = "{tips:{isOk:true/false,msg:'成功/失败原因',tipscode:'失败时错误码'},data:数据对象}")
    })
    @RequestMapping(value="/queryById",method=RequestMethod.GET)
    public Result queryById(FormField formField) {
        FormField data = (FormField) formFieldService.getById(formField);
        return Result.ok().setData(data);
    }

}
